package com.miku.ai.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.miku.ai.common.ErrorCode;
import com.miku.ai.exception.ThrowUtils;
import com.miku.ai.model.dto.question.QuestionContentDTO;
import com.miku.ai.model.entity.App;
import com.miku.ai.model.entity.Question;
import com.miku.ai.model.entity.ScoringResult;
import com.miku.ai.model.entity.UserAnswer;
import com.miku.ai.model.vo.QuestionVO;
import com.miku.ai.model.vo.ScoringResultVO;
import com.miku.ai.service.AppService;
import com.miku.ai.service.QuestionService;
import com.miku.ai.service.ScoringResultService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义测评类应用评分策略
 */
@ScoringSrategyConfig(appType = 1,scoringStrategy = 0)
public class CustomTestScoringStrategy implements ScoringStrategy {

    @Resource
    private QuestionService questionService;

    @Resource
    private AppService appService;

    @Resource
    private ScoringResultService scoringResultService;

    //学习风格评估
    @Override
    public UserAnswer doScore(List<String> choices, App app) throws Exception {
        //1. 根据id查询到题目和结果信息
        Long appId = app.getId();
        ThrowUtils.throwIf(appId == null, ErrorCode.PARAMS_ERROR);
        Question question = questionService.getOne(Wrappers.<Question>lambdaQuery().eq(Question::getAppId, appId));

        List<ScoringResult> scoringResults = scoringResultService.list(Wrappers.<ScoringResult>lambdaQuery().eq(ScoringResult::getAppId, appId));

        //2.统计用户每个选项对应的熟悉个数：如 A=10个 B=5个
        //初始化HashMap，用于存储每个选项的个数
        Map<String,Integer> optionCount=new HashMap<>();

        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContentDTO> questionContent = questionVO.getQuestionContent();
        //遍历题目列表
        for (QuestionContentDTO questionContentDTO : questionContent) {
            //遍历答案列表
            for (String answer : choices) {
                for (QuestionContentDTO.Option option : questionContentDTO.getOptions()) {
                    //如果答案和选型key相匹配
                    if (answer.equals(option.getKey())) {
                        //获取选型result的值
                        String result = option.getResult();
                        //如果result属性不在optionCount中,则初始化为0
                        if (!optionCount.containsKey(result)) {
                            optionCount.put(result, 0);
                        //将result对应的值加1
                        optionCount.put(result, optionCount.get(result) + 1);
                        }
                    }
                }
            }
        }
        //3.遍历每种评分结果，计算哪个结果的评分更高
        int maxScore=0;
        ScoringResult maxScoreResult = scoringResults.get(0);
        //遍历评分结果列表
        for (ScoringResult result : scoringResults) {
            //计算当前评分结果的分数
            ScoringResultVO resultVO = ScoringResultVO.objToVo(result);
            int score = resultVO.getResultProp().stream().mapToInt(prop -> optionCount.getOrDefault(prop, 0)).sum();

            //如果当前评分结果的分数比之前的最高分数高，则更新最高分数和最高分数对应的评分结果
            if (score > maxScore) {
                maxScore = score;
                maxScoreResult = result;
            }
        }
        //4.构造返回值，填充答案对象的属性
        UserAnswer userAnswer=new UserAnswer();
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(maxScoreResult.getId());
        userAnswer.setResultName(maxScoreResult.getResultName());
        userAnswer.setResultDesc(maxScoreResult.getResultDesc());
        userAnswer.setResultPicture(maxScoreResult.getResultPicture());
        userAnswer.setResultScore(maxScore);

        return userAnswer;
    }
}
